package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ushine.web.base.facade.IUserRedisFacade;
import com.ushine.web.base.facade.IUserRolePermissionFacade;
import com.ushine.web.base.mapper.SecurityUserMapper;
import com.ushine.web.base.model.system.UserDO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: yls
 * @Date: 2021/8/18 14:42
 * @Description: 获取用户信息
 * @Version 1.0
 */
@Slf4j
@Service
@Transactional(rollbackFor = {Exception.class})
public class SecurityUserServiceImpl implements UserDetailsService, UserDetailsPasswordService {

    @Resource
    private SecurityUserMapper securityUserMapper;

    @Resource
    private IUserRolePermissionFacade userRolePermissionFacade;

    @Resource
    private IUserRedisFacade userRedisFacade;

    @SneakyThrows
    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO userDO = userRedisFacade.getUserInfo(username);
        log.info("用户信息：" + userDO);
        if (userDO == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        return userDO;
    }


    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername, userDetails.getUsername());
        UserDO userDO = securityUserMapper.selectOne(queryWrapper);
        userDO.setPassword(newPassword);
        securityUserMapper.insert(userDO);
        return userDO;
    }


}
